package com.sso.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class LoginServlet extends HttpServlet {
    private String domains;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        domains = config.getInitParameter("domains");
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if ("/login".equals(request.getServletPath())) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String source = request.getParameter("source");

            if (source == null || "".equals(source)) {
                String referer = request.getHeader("referer");
                source = referer.indexOf("source=") > -1 ? referer.substring(referer.indexOf("source=") + 7) : referer;
            }

            if (username.equals(password)) { // 如果登录用户名和密码相同就判断登录成功
                String ticket = UUID.randomUUID().toString().replace("-", "");
                System.out.println("************************ " + ticket + " ************************");
                // 登录成功，重定向到 source 并且把 ticket 和 domains 带过去
                response.sendRedirect(source + "/main?ticket=" + ticket + "&domains=" +
                        domains.replace(source + ",", "").replace("," + source, "").replace(source, ""));
            } else {
                request.setAttribute("source", source);
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
        } else if (Objects.equals("/ssoLogin", request.getServletPath())) {
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }
}
